<?php

/**
 * alltosun.com 开放平台公用函数库 common.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 郭莹雪 (guoyx@alltosun.com) $
 * $Date: 2011-12-21 下午04:57:20 $
*/

//require_once 'sinaweibo_v2/common.php';

/**
 * 获取关联网站的id
 * @param string $site_name
 */
function get_site_id($site_name)
{
    return _uri('connect_site', array('site_name'=>$site_name), 'id');
}

/**
 * 获取关联网站的名称
 * @param int $site_id
 */
function get_site_name($site_id)
{
    return _uri('connect_site', array('id'=>$site_id), 'site_name');
}

/**
 * 根据refresh_token刷新access_token
 * @param int $user_id
 * @param string $site_name
 */
function refresh_login($user_id, $site_name)
{
    if (!$user_id) {
        return false;
    }

    if ($site_name == 'qqweibo') {
        $connect_info = _uri('connect_qq', array('user_id'=>$user_id, 'connect_site_id'=>get_site_id($site_name)));
    } else {
        $connect_info = _uri('connect', array('user_id'=>$user_id, 'connect_site_id'=>get_site_id($site_name)));
    }

    if (!$connect_info) {
        return false;
    }
    // 刷新access_token
    if ($site_name == 'kaixin') {
        require_once MODULE_PATH.'/openapi/helper/kaixin/kxClient.php';
        $connection = new KXClient();
        $token = $connection->getAccessTokenFromRefreshToken($connect_info['refresh_token'], Config::get('kaixin_scope'));
    } elseif ($site_name == 'renren') {
        require_once MODULE_PATH.'/openapi/helper/renren/requires.php';
        global $config;
        $data = array(
            'grant_type' => 'refresh_token',
            'refresh_token' => $connect_info['refresh_token'],
            'client_id' => $config->APIKey,
            'client_secret' => $config->SecretKey
        );
        $token = AnCurl::post('https://graph.renren.com/oauth/token', $data);
        $token = json_decode($token, true);
    } elseif ($site_name == 'qqweibo') {
        $_SESSION[$site_name]['last_key']['oauth_token'] = $connect_info['oauth_token'];
        $_SESSION[$site_name]['last_key']['oauth_token_secret'] = $connect_info['oauth_token_secret'];
        $_SESSION[$site_name]['last_key']['open_id'] = $connect_info['connect_open_id'];
    }

    if (!empty($token)) {
        $_SESSION[$site_name]['token']['access_token'] = $token['access_token'];
        $_SESSION[$site_name]['token']['connect_user_id'] = $connect_info['connect_user_id'];
        _model(get_connect_table($site_name))->update(array('user_id'=>$user_id, 'connect_site_id'=>get_site_id($site_name)), array('access_token'=>$token['access_token'], 'expires_time'=>$token['expires_in']+time()));
    }
    return true;
}

/**
 * 获取用户链接的网站
 * @param int $user_id
 * @return multitype:|number
 */
function get_user_connect($user_id)
{
    if (!$user_id) {
        return array();
    }

    return get_connect_list();
}

/**
 * 用户绑定更改原来的相关信息
 * @param int $user_id 当前用户id
 * @param int $connect_user_id 之前用户id
 */
function update_bind_info($user_id, $past_user_id, $site_name)
{
    _model('user')->update(array('id'=>$past_user_id), array('status'=>2));
    _model('connect_setting')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id));
    // 更改授权绑定的id  可能原来绑定过  所以要把所有的都改过来
    _model('connect_qq')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id));
    _model('connect')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id));
    // 更改评论的用户id
    _model('comment')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id, 'update_time'=>'update_time'));
    // 更改统计信息
    _model('statistics_user')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id, 'update_time'=>'update_time'));
    _model('statistics_day_user')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id, 'update_time'=>'update_time'));
    _model('statistics_hour_user')->update(array('user_id'=>$past_user_id), array('user_id'=>$user_id, 'update_time'=>'update_time'));
}

function sync_connect($comment_id, $content, $connect_list, $page_info)
{
    $user_id = get_user_id();
    $error_info = '';
    $connect_res_id = 0;
    foreach ($connect_list as $k=>$v) {
        // 是否同步成功
        $success = 0;
        try {
            if ($v == 'renren') {
                $info = AnOpenApi('renren')->update(sync_content_display($content, $v, $comment_id, $page_info));
                //mail('liw@alltosun.com', 'renren-status', var_export($info, TRUE));
                if (!empty($info['result']) && $info['result'] == 1) {
                    $status_info = AnOpenApi('renren')->show('');
                    $connect_res_id = $status_info['status_id'];
                    $success = 1;
                } else {
                    $error_info .= '人人开放平台信息同步错误 ';
                }
            } elseif ($v == 'kaixin') {
                $info = AnOpenApi('kaixin')->update(sync_content_display($content, $v, $comment_id, $page_info));
                //mail('liw@alltosun.com', 'kaixin-status', var_export($info, true));
                if ($info['httpcode'] == 200) {
                    $connect_res_id = $info['response']['rid'];
                    $success = 1;
                } else {
                    $error_info .= '开心开放平台信息同步错误';
                }
            } elseif ($v == 'qqweibo') {
                // @FIXME 在embed.php中Tencent.php $_SESSION授权信息设置在这里获取不到，不知道为什么，暂时再获取一遍
                $check_info = AnOpenApi('qqweibo')->authorize();
                if ($check_info['status'] != 'ok') {
                    $error_info .= '腾讯微博开放平台授权信息错误';
                    continue;
                }
                $info = AnOpenApi('qqweibo')->update(sync_content_display($content, $v, $comment_id, $page_info));
                if ($info['errcode'] == 0) {
                    $connect_res_id = $info['data']['id'];
                    $success = 1;
                } else {
                    $error_info .= '腾讯微博开放平台信息同步错误';
                }
            } elseif ($v == 'sinaweibo') {
                $info = AnOpenApi('sinaweibo')->update(sync_content_display($content, $v, $comment_id, $page_info));
                if (!empty($info['error_code'])) {
                    $error_info .= '新浪微博开放平台信息同步错误';
                } else {
                    $connect_res_id = $info['id'];
                    $success = 1;
                }
            }
            _model('connect_res')->create(array('connect_res_id'=>$connect_res_id, 'connect_site_id'=>get_site_id($v), 'res_name'=>'comment', 'connect_id'=>get_connect_id($v, $user_id), 'res_id'=>$comment_id));

            // 同步数量统计
            if ($success == 1) {
                $statistics_arr = array(
                        'type'    => 'add_sync_num',
                        'page_id' =>$page_info['id'],
                        'user_id' => get_user_id(),
                        'site_id' => $page_info['site_id'],
                        'sync_site_name' => $v
                );
                _widget('statistics')->record($statistics_arr);
            }
        } catch (Exception $e) {
            if (ONDEV) {
                exit(var_dump($e));
            }
        }
    }
    return $error_info;
}

function sync_content_display($content, $site_name, $comment_id, $page_info)
{
    if (!$site_name) {
        return $content;
    }
    if ($site_name == 'sinaweibo') {
        $content = unset_kaixin($content);
        $content = unset_renren($content);
        $content = unset_qqweibo($content);
    } elseif ($site_name == 'qqweibo') {
        $content = unset_kaixin($content);
        $content = unset_renren($content);
        $content = unset_sinaweibo($content);
    } elseif ($site_name == 'renren') {
        $content = unset_kaixin($content);
        $content = unset_sinaweibo($content);
        $content = unset_qqweibo($content);
    } elseif ($site_name == 'kaixin') {
        $content = unset_renren($content);
        $content = unset_sinaweibo($content);
        $content = unset_qqweibo($content);
    }

    // 加入回流量点击统计  短链10个字+亦云社交评论云服务  = 20个字
    $content = AnString::cutStr($content, 117, '...');
    $yiy_page_url = $page_info['url'];
    $pre_statistics_name = Config::get('pre_statistics_name');
    $statistics_comment_id_name = Config::get('statistics_comment_id_name');
    if (stripos($yiy_page_url, '?') !== false) {
        $yiy_page_url .= '&'.$pre_statistics_name.'from='.$site_name.'&'.$statistics_comment_id_name.'='.$comment_id;
    }else {
        $yiy_page_url .= '?'.$pre_statistics_name.'from='.$site_name.'&'.$statistics_comment_id_name.'='.$comment_id;
    }
    $content .=  ' '. $yiy_page_url.'  -亦云社交评论云服务';

    return $content;
}

function unset_renren($content)
{
    return preg_replace('/\([^\#][\S\s]*?\)/', '', $content);
}
function unset_kaixin($content)
{
    return preg_replace('/\(\#[\S\s]*?\)/', '', $content);
}
function unset_qqweibo($content)
{
    // @FIXME 好像不行   没办法判断结束呀
    return preg_replace('/\/.*?/', '', $content);
}
function unset_sinaweibo($content)
{
    return preg_replace('/\[[\S\s]*?\]/', '', $content);
}

function get_connect_list()
{
    $user_id = get_user_id();
    $connect_info = _model('connect_setting')->getFields('res_name', array('user_id'=>$user_id, 'default_sync'=>1));
    return $connect_info;
}

function get_connect_id($site_name, $user_id)
{
    $table = get_connect_table($site_name);
    $id = _uri($table, array('user_id'=>$user_id, 'connect_site_id'=>get_site_id($site_name)), 'id');
    return $id;
}

function get_connect_user_id($site_name, $user_id)
{
    $table = get_connect_table($site_name);
    if ($site_name == 'qqweibo') {
        $user_id = _uri($table, array('user_id'=>$user_id, 'connect_site_id'=>get_site_id($site_name)), 'connect_user_name');
    } else {
        $user_id = _uri($table, array('user_id'=>$user_id, 'connect_site_id'=>get_site_id($site_name)), 'connect_user_id');
    }
    return $user_id;
}

function get_connect_table($site_name)
{
    if ($site_name == 'qqweibo') {
        $table = 'connect_qq';
    } else {
        $table = 'connect';
    }
    return $table;
}

function get_category_name($category_id)
{
    return _uri('emotion_category', $category_id, 'title');
}

/**
 * 解析表情
 * @param string $content
 */
function content_display($content)
{
    $pattern = '/'.Config::get('sinaweibo_emotion_pattern').'|'.Config::get('qqweibo_emotion_pattern')
               .'|'.Config::get('renren_emotion_pattern').'|'.Config::get('kaixin_emotion_pattern').'/u';

    preg_match_all($pattern, $content, $matches);

    if (!$matches) return true;

    _model('emotion')->lifetime = 3600*24;
    $emotion_list = _model('emotion')->getList(array('1'=>1));

    $list = array();
    foreach ($emotion_list as $v) {
        $list[$v['value']] = '<img src='.$v['url'].'>';
    }

    foreach ($matches[0] as $v) {
        if (isset($list[$v])){
            $content = str_replace($v, $list[$v], $content);
        }
    }

    return $content;
}
?>